package com.lz.bank.service.impl;

import com.lz.bank.bean.Account;
import com.lz.bank.dao.AccountDao;

import com.lz.bank.exceptions.MoneyNotEnoughException;
import com.lz.bank.exceptions.TransferException;
import com.lz.bank.service.AccountService;
import com.lz.bank.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

public class AccountServiceImpl implements AccountService {
    //AccountDao accountDao = new AccountDaoImpl();

    @Override
    public void transfer(String fromActno, String toActno, double money)
            throws MoneyNotEnoughException, TransferException {
        //在业务层控制事务
        SqlSession sqlSession = SqlSessionUtil.openSession();
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
        //System.out.println(sqlSession);
        //1.判断余额
        Account fromAct = accountDao.selectOneByActno(fromActno);

        if (money > fromAct.getBalance()) {
            throw new MoneyNotEnoughException("余额不足，转账失败");
        }

        Account toAct = accountDao.selectOneByActno(toActno);
        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);
        //更新数据库
        int count = accountDao.updateByActno(fromAct);
        //人为异常
//        String str = null;
//        str.toString();
        count += accountDao.updateByActno(toAct);
        if (count != 2){
            throw new TransferException("转账失败，未知原因");
        }

        sqlSession.commit();
        SqlSessionUtil.close(sqlSession);
    }
}
